import type { EChartsOption, ECharts } from 'echarts'

import { useDebounceFn, useResizeObserver } from '@vueuse/core'
import * as echarts from 'echarts'

type BasicProps = {
  el: MaybeRef<HTMLElement>,
  theme?: string,
}

export function useECharts({
  el,
  theme = 'light',
}: BasicProps) {
  let chartInstance: Nullable<ECharts> = null

  // resize
  const resize = () => {
    chartInstance?.resize()
  }
  const resizeFn: Fn = useDebounceFn(resize, 200)

  // 初始化实例
  function initChart(th = theme) {
    const elDom = unref(el)
    if (!elDom) {
      return
    }
    chartInstance = echarts.init(elDom, th)
    useResizeObserver(elDom, resizeFn)
  }

  // 配置
  let cacheOptions = {}
  function setOptions(options: EChartsOption = cacheOptions) {
    cacheOptions = options
    const elDom = unref(el)
    if (!elDom || elDom.clientHeight === 0 || elDom.clientWidth === 0) {
      return
    }
    if (!chartInstance) {
      initChart(theme)
      if (!chartInstance) {
        return
      }
    }
    chartInstance.setOption(cacheOptions, true)
  }

  onBeforeUnmount(() => {
    if (!chartInstance) return
    chartInstance.dispose()
    chartInstance = null
  })

  // 改变 theme
  function changeChartTheme(theme: string) {
    if (chartInstance) {
      chartInstance.dispose()
      initChart(theme)
      setOptions()
    }
  }

  // 获取实例
  function getInstance() {
    return chartInstance
  }

  return {
    setOptions,
    changeChartTheme,
    resize,
    getInstance
  }
}
